<template>
  <div class="dashboard-container">
    <el-card>
      <!-- 头部搜索框 -->
      <el-row type="flex" justify="center">
        <el-col :span="20">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="关键字">
              <el-input v-model="table.keyword"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="table.state" placeholder="请选择状态">
                <el-option label="已启用" value="1"></el-option>
                <el-option label="已禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="onclear">清除</el-button>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="4">
          <el-button type="success" @click="edit">
            <i class="el-icon-edit"></i>
            新增技巧
          </el-button>
        </el-col>
      </el-row>
      <!-- 头部搜索结束 -->
      <!-- 内容数量提示 -->
      <el-alert :title="this.alert" type="info" show-icon :closable="false">
      </el-alert>
      <!-- 内容数量提示结束 -->
      <!-- 表格内容区域 -->
      <el-table :cell-style="rowstyle" :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column label="标题" width="300">
          <template slot-scope="{ row }">
            <el-row type="flex" justify="space-between">
              <el-col>
                <span>{{ row.title }}</span>
              </el-col>
              <el-col :span="3">
                <i
                  v-if="row.videoURL"
                  class="el-icon-video-camera"
                  style="color: #409eff"
                  @click="view(row.videoURL)"
                ></i>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="visits" label="阅读数" width="150">
        </el-table-column>
        <el-table-column prop="username" label="录入人"> </el-table-column>
        <el-table-column label="录入时间">
          <template slot-scope="{ row }">
            {{ row.createTime | parseTimeByString("{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{ row }">
            {{ row.state === 1 ? "已启用" : "已禁用" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" @click="yulan(row)"
              >预览</el-button
            >
            <el-button size="mini" type="text" @click="jinyong(row)">{{
              row.state === 1 ? "禁用" : "启用"
            }}</el-button>
            <el-button
              size="mini"
              type="text"
              @click="xiugai(row)"
              :disabled="row.state ? true : false"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="shanchu(row)"
              :disabled="row.state ? true : false"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格内容区域结束 -->
      <!-- 分页组件 -->
      <el-row type="flex" justify="end">
        <el-col :span="8">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizepage"
            :current-page.sync="table.page"
            layout="prev, pager, next, sizes, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="10"
            :total="this.number"
          >
          </el-pagination>
        </el-col>
      </el-row>
      <!-- 视频播放组件 -->
      <el-dialog
        title="视频"
        :visible.sync="dialogPlay"
        width="30%"
        @close="closeDialog"
      >
        <video
          :src="videoUrl"
          controls
          autoplay
          ref="dialogVideo"
          width="100%"
        ></video>
      </el-dialog>
      <!-- // 预览组件 -->
      <artPreview ref="prev" :show="showpre" @close="showpre = false" />
      <!-- 新增/编辑组件 -->
      <el-dialog
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose">
          <span slot="title">{{ updataid ? '编辑' : '新增' }}</span>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
            <el-row type="flex">
              <el-col :span="20">
                <el-form-item label="文章标题" prop="title">
                  <el-input v-model="ruleForm.title"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex">
              <el-col :span="20">
                <el-form-item label="文章内容" prop="articleBody">
                  <quill-editor @blur="textblur" ref="myTextEditor" v-model="ruleForm.articleBody" :options="editorOption"></quill-editor>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex">
              <el-col :span="20">
                <el-form-item label="视频链接" prop="videoURL">
                  <el-input v-model="ruleForm.videoURL"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="btnok">确 定</el-button>
          </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { list, changeState, remove, update, add, detail } from '@/api/hmmm/articles'
import artPreview from '../components/articles-preview'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
  export default {
    name: 'articles',
    data() {
      return {
        ruleForm: {
          title: '',
          articleBody: '',
          videoURL: ''
        },
        rules: {
          title: [
            { required: true, message: '请输入文章标题', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          articleBody: [
            { required: true, message: '请输入文章内容', trigger: 'blur' }
          ]
        },
        editorOption: {
           placeholder: '',
           modules:{
              toolbar:[
                ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
                ['blockquote', 'code-block'],     //引用，代码块
                [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
                // [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
                [{ 'indent': '-1'}, { 'indent': '+1' }],     // 缩进
                // [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
                [{ 'align': [] }],    //对齐方式
                ['clean'],    //清除字体样式
                ['image','video']    //上传图片、上传视频
              ]
            }
         },
        updataid: null, // 编辑弹层的id
        dialogVisible: false, // 新增编辑的弹层
        showpre: false, // 预览弹层
        dialogPlay: false,
        videoUrl: null, // 视频地址
        alert: '',  // 提示数量
        number: 0, // 数据总户数量
        tableData:[],
        formInline: {
          user: '',
          region: ''
        },
        table: {
          page: 1,  // 页码
          pagesize: 10,  // 每页数量
          keyword: null,
          state: null
        }
      }
    },
    components: {
      artPreview,
      quillEditor
    },
    created() {
      this.list(this.table)
    },
    methods: {
      btnok(){
        this.$refs.ruleForm.validate( async (isok) => {
          if (isok) {
            if(this.updataid) {
            // 编辑
              await update(this.ruleForm)
            this.list(this.table)
            this.$message({
              message: '修改成功',
              type: 'success'})
          } else {
            // 新增
            await add(this.ruleForm)
            this.list(this.table)
            this.$message({
              message: '添加成功',
              type: 'success'});
            }
          }else {
            console.log('error submit!!');
            return false;
          }
          this.handleClose() // 清除内容以及校验规则
        }
        )

      },
      textblur(){
        this.$refs.ruleForm.validateField('articleBody');
      },
      async list(obj) {
        const data = await list(obj)
        this.tableData=data.data.items
        this.number = data.data.counts
        this.alert = `数据一共${ data.data.counts }条`
      },
      rowstyle({row, column, rowIndex, columnIndex}) {
        if(row.state === 0 && columnIndex === 5 ) {
          return "color: red"
        } else if (row.state === 1 && columnIndex === 5) {
          return "color: #67C23A"
        }
      },
      handleCurrentChange(val) {
        this.table.page = val
        this.list(this.table)
      },
      onclear() {
        this.table = {
          page: 1,  // 页码
          pagesize: 10,  // 每页数量
          keyword: null,
          state:null
        }
      },
      sizepage(val){
        this.table.pagesize = val
        this.list(this.table)
      },
      onSubmit() {
        this.list(this.table)
      },
      view(val){
        // 视频播放
        this.dialogPlay = true
        this.videoUrl = val
      },
      closeDialog(){
        this.videoUrl = null
        this.$refs.dialogVideo.pause()
      },
      edit() {
        // 新增技巧
        this.dialogVisible = true
      },
      async yulan(row) {
        // 预览
        this.showpre = true
        this.$refs.prev.detail(row)
      },
      async jinyong(row) {
        const { id, state } = row
        try{
          await changeState({ id:id, state: state === 1 ? 0 : 1  })
          this.list(this.table)
          if(state === 1) {
            this.$message({
               message: '禁用成功',
                type: 'warning'
            })
          } else {
            this.$message({
              message: '启用成功',
              type: 'success'});
          }
        } catch(err) {
          this.$message('禁用失败，请稍后重试');
        }
        
      },
      async xiugai(row) {
        this.updataid = row.id
        this.dialogVisible = true
        const { data } = await detail(row)
        this.ruleForm = { ...data }
        this.updataid = data.id
      },
       shanchu(row) {
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try{
              await remove({ id:row.id })
              this.list(this.table)
            } catch (err) {
              this.$message({
              type: 'info',
              message: '删除失败'
            })
            }
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      handleClose() {
        this.updataid = null
        this.dialogVisible = false,
        this.ruleForm= {
          name: '',
          text: '',
          view: ''
        },
        this.$refs.ruleForm.resetFields()
      },
      onEditorChange({ editor, html, text }) {
            this.ruleForm.text = html;
        },
    }
  }
</script>

<style>
.dashboard-container {
  margin: 10px;
}
.el-table {
  margin-top: 15px;
}
.el-row--flex {
  margin-top: 15px;
}

.ql-editor {
  height: 200px;
}
</style>
